package com.lilei.bigdata.mr.provienceflow;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class FlowCount {

    static class FlowCountMapper extends Mapper<LongWritable, Text,Text, FlowBean>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();

            String[] fields = line.split("\t");
            String phoneNum = fields[1];
            long upFlow = Long.parseLong(fields[fields.length-3]);
            long dFlow = Long.parseLong(fields[fields.length-2]);
            context.write(new Text(phoneNum),new FlowBean(upFlow,dFlow));
        }
    }

    static class FlowCountReducer extends Reducer<Text, FlowBean,Text, FlowBean>{
        @Override
        protected void reduce(Text key, Iterable<FlowBean> values, Context context) throws IOException, InterruptedException {
            long sum_upFlow = 0;
            long sum_dFlow = 0;

            for (FlowBean flowBean:values){
                sum_upFlow+=flowBean.getUpFlow();
                sum_dFlow+=flowBean.getdFlow();
            }

            context.write(key,new FlowBean(sum_upFlow,sum_dFlow));
        }
    }


    public static void main(String[] args) throws Exception{
        Configuration configuration = new Configuration();
        Job job =   Job.getInstance(configuration);


        //指定本程序的jar包所在的本地路径
        job.setJarByClass(FlowCount.class);

        //指定本业务job要使用的mapper/Reducer业务类
        job.setMapperClass(FlowCountMapper.class);
        job.setReducerClass(FlowCountReducer.class);

        //指定mapper输出数据的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(FlowBean.class);

        //指定最终输出的kv类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FlowBean.class);

        //指定我们自定义的数据分区器
        job.setPartitionerClass(ProviencePartitioner.class);
        job.setNumReduceTasks(5);

        //指定job的输入原始文件所在目录
        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        //将job中配置的相关参数，以及job所用的java类所在的jar包，提交给yarn去运行\

        boolean res = job.waitForCompletion(true);
        System.exit(res?0:1);
    }
}
